#include "HandleRequest.h"


extern UserManager user_manager;
extern MyServSocket MS;
extern ChattingRoomManager chat_room_manager;
extern NotificationManager notify_manager;

void ResponseClient(const int &sockfd, const json &response_json){
    if(sockfd<0){
        PRINTF_LOG_AND_DEBUG(LOG_ERR,"ResponseClient:Invalid sockfd:%d\n",sockfd);
        return ;
    }
    MS.SendToClient(sockfd,response_json.dump());
}


void handle_request(const std::string& request_str,const int& sockfd)
{
    json request_json;


    try{
      request_json = json::parse(request_str);
    }
    catch(const std::exception& e){
        PRINTF_LOG_AND_DEBUG(LOG_ERR, "Invalid request: %s\n", e.what());
        handle_unknown_request(sockfd);
        return;
    }

    #ifdef DEBUG
    cout<<request_json.dump(4)<<endl;
    #endif

    if(request_json.find("request_type") == request_json.end()){
        handle_unknown_request(sockfd);
        return;
    }
    int request_type = request_json["request_type"].get<int>();

    
    switch(request_type){
        case LOGIN://1
            handle_login_request(request_json,sockfd);
            break;
        case CREAT_USER://1
            handle_CreateUser_request(request_json,sockfd);
            break;
        case LOGOUT://1
            handle_logout_request(request_json,sockfd);
            break;
        case GET_CHANNEL_LIST://1
            handle_getChatList_request(request_json,sockfd);
            break;
        case JOIN_CHANNEL:
            handle_joinChat_request(request_json,sockfd);//1
            break;
        case SEND_MSG:
            handle_message_request(request_json,sockfd);//1
            break;
        case CREATE_CHANNEL:
            handle_createChat_request(sockfd,request_json);//1
            break;
        case EXIT_CHANNEL:
            handle_exitChat_request(sockfd,request_json);//1
            break;
        case DEL_CHANNEL:
            handle_delChat_request(sockfd,request_json);//1
            break;
        case GET_CHANNEL_INFO:
            handle_getChatInfo_request(sockfd,request_json);//1
            break;
        case GET_NEWER_MSG:
            handle_getLatestMsg_request(sockfd,request_json);//1
            break;
        case INVITE_USER:
            handle_invite_request(sockfd,request_json);
            break;
        case AGREE_JOIN_CHANNEL:
            handle_accept_request(sockfd,request_json);
            break;
        case DISAGREE_JOIN_CHANNEL:
            handle_refuse_request(sockfd,request_json);
            break;  
        
        default:
            handle_unknown_request(sockfd);
    }
}

void handle_login_request(const json& request,const int& sockfd){
    int result;
    json response;
    response["response_type"]=LOGIN;
    response["user_id"]=request["user_id"];

    if(request.find("user_id") == request.end() || request.find("pwd") == request.end()){
        result=4;
    }
    else{result=user_manager.login(request["user_id"],request["pwd"],sockfd);}

    response["result"]=result;
    switch (result)
    {
    case 0:
        response["msg"]="登录成功";
        break;  
    case 1:
        response["msg"]="用户不存在";
        break;
    case 2:
        response["msg"]="密码错误";
        break;
    case 3:
        response["msg"]="文件错误";
        break;
    case 4:
        response["msg"]="参数缺失";
    default:
        break;
    }
    ResponseClient(sockfd,response);
}

void handle_CreateUser_request(const json& request,const int& sockfd){
    json response;
    user_manager.createUser(request["name"],request["pwd"]);
    response["response_type"]=CREAT_USER;
    response["result"]=0;
    response["msg"]="创建成功";
    response["id"]=user_manager.get_user_count();
    ResponseClient(sockfd,response);
}


void handle_logout_request(const json& request_json,const int& sockfd){
    json response;
    response["response_type"]=LOGOUT;
    response["user_id"]=request_json["user_id"];
    response["result"]=0;
    response["msg"]="退出成功";

    user_manager.logout(request_json["user_id"]);
    ResponseClient(sockfd,response);
}

void handle_getChatList_request(const json& request_json,const int& sockfd){
    json response;
    response["response_type"]=GET_CHANNEL_LIST;
    response["result"]=0;
    response["user_id"]=request_json["user_id"];
    user_manager.get_chat_list(request_json["user_id"],response["chat_list"]);

    ResponseClient(sockfd,response);
}

void handle_joinChat_request(const json& request_json,const int& sockfd){
    json response;
    response["response_type"]=JOIN_CHANNEL;
    response["user_id"]=request_json["user_id"];
    response["chat_room_id"]=request_json["chat_room_id"];
    int result=chat_room_manager.JoinChatRoom(request_json["chat_room_id"],request_json["user_id"],user_manager.get_user_name(request_json["user_id"]));
    response["result"]=result;

    switch(result){
        case static_cast<int>(ChatRoomErr::SUCCESS):
            response["msg"]="加入成功";
            user_manager.add_chat_list(request_json["user_id"],request_json["chat_room_id"]);

            break;
        case static_cast<int>(ChatRoomErr::NO_SUCH_CHAT_ROOM):
            response["msg"]="不存在该聊天室";
            break; 
        case static_cast<int>(ChatRoomErr::ALLREADY_IN_ROOM):
            response["msg"]="已经在该聊天室";
            break;
        default:
            response["msg"]="加入失败";
            break;
    }

    ResponseClient(sockfd,response);
}


void handle_message_request(const json& request_json,const int& sockfd){
    json response;
    int result;
    response["response_type"]=SEND_MSG;
    
    // #ifdef DEBUG
    // cout<<request_json.dump(4)<<endl;
    // #endif
    
    shared_ptr<Msg> msg(new Msg(request_json["Msg"]));
    result=chat_room_manager.AddChatMsg(msg->get_chat_room_id(),msg);

    response["result"]=result;
    switch (result)
    {
        case static_cast<int>(ChatRoomErr::SUCCESS):
            response["msg"]="发送成功";
            ULMNN_Manager::get_instance()->add_num_for_user_in_chat_room(msg->get_sender_id(),msg->get_chat_room_id(),msg->get_time());
            break;
        case static_cast<int>(ChatRoomErr::NO_SUCH_CHAT_ROOM):
            response["msg"]="不存在该聊天室";
            break;
        default :
            response["msg"]="发送失败";
            break;
    }

    ResponseClient(sockfd,response);
}

void handle_createChat_request(const int&fd,const json& request_json){
    json response;
    #ifdef DEBUG
    cout<<request_json.dump(4)<<endl;
    #endif

    string chat_room_id=chat_room_manager.CreateChatRoom(request_json["user_id"].get<int>(),request_json["chat_room_name"]);
    response["response_type"]=CREATE_CHANNEL;
    if(chat_room_id.empty()){
        response["result"]=1;
        response["msg"]="创建失败";
    }
    else{
        response["result"]=0;
        response["msg"]="创建成功";

        user_manager.add_chat_list(request_json["user_id"],chat_room_id);
    }
    response["chat_room_id"]=chat_room_id;
    ResponseClient(fd,response);
}


void handle_exitChat_request(const int&socketfd,const json& request_json){
    json response;
    response["response_type"]=EXIT_CHANNEL;
    response["chat_room_id"]=request_json["chat_room_id"];
    int result=chat_room_manager.ExitChatRoom(request_json["chat_room_id"],request_json["user_id"]);
    response["result"]=result;

    switch (result)
    {
    case static_cast<int>(ChatRoomErr::SUCCESS):       /* code */
        response["msg"]="退出成功";
        break;
    case static_cast<int>(ChatRoomErr::NO_SUCH_CHAT_ROOM):
        response["msg"]="不存在该聊天室";
        break;
    case static_cast<int>(ChatRoomErr::NO_SUCH_USER):
        response["msg"]="用户不在该聊天室";
        break;
    default:
        response["msg"]="退出失败";
        break;
    }

    ResponseClient(socketfd,response);
}

void handle_delChat_request(const int&socketfd, const json& request_json){
    json response;
    response["response_type"]=DEL_CHANNEL;
    response["chat_room_id"]=request_json["chat_room_id"];

    int result=chat_room_manager.DeleteChatRoom(request_json["chat_room_id"],request_json["user_id"]);
    
    response["result"]=result;

    switch(result){
        case static_cast<int>(ChatRoomErr::SUCCESS):
            response["msg"]="删除成功";
            break;
        case static_cast<int>(ChatRoomErr::NO_SUCH_CHAT_ROOM):
            response["msg"]="不存在该聊天室";
            break;
        case static_cast<int>(ChatRoomErr::NOT_OWNER):
            response["msg"]="不是该聊天室的创建者";
            break;
        default:
            response["msg"]="删除失败";
            break;
    }

    ResponseClient(socketfd,response);
}

void handle_getChatInfo_request(const int&socketfd, const json& request_json){
    json response;
    response["response_type"]=GET_CHANNEL_INFO;
    response["chat_room_id"]=request_json["chat_room_id"];

    int result=chat_room_manager.QuickLoadChatContent(request_json["chat_room_id"],response["chat_room_info"]);
    response["result"]=result;

    switch (result)
    {
        case static_cast<int>(ChatRoomErr::SUCCESS):
            response["msg"]="获取成功";
            break;
        case static_cast<int>(ChatRoomErr::NO_SUCH_CHAT_ROOM):
            response["msg"]="不存在该聊天室";
            break;
        default:
            response["msg"]="获取失败";
            break;
    }
    ResponseClient(socketfd,response);
}

void handle_getLatestMsg_request(const int&sockfd, const json& request_json){
    json response;
    response["response_type"]=GET_NEWER_MSG;

    int result=chat_room_manager.GetLatestChatMsg(request_json["chat_room_id"],request_json["msg_num"].get<int>(),response["chat_msg"]);
    response["result"]=result;
    switch(result){
        case static_cast<int>(ChatRoomErr::SUCCESS):
            response["msg"]="获取成功";
            break;
        case static_cast<int>(ChatRoomErr::NO_SUCH_CHAT_ROOM):
            response["msg"]="不存在该聊天室";
            break;
        default:
            response["msg"]="获取失败";
            break;
    }

    ResponseClient(sockfd,response);
}

void handle_invite_request(const int&sockfd, const json& request_json){
    json response;
    response["response_type"]=INVITE_USER;
    response["result"]=0;
    response["invite_user_id"]=request_json["invite_user_id"];
    response["msg"]="邀请发送成功";
    
    NotificationManager::get_instance()->add_notify(request_json["invite_user_id"],make_unique<InviteNotify>
        (request_json["user_id"],request_json["invite_user_id"],request_json["chat_room_id"],request_json["content"],request_json["time"])
    );
    ResponseClient(sockfd,response);
}


void handle_accept_request(const int &sockfd, const json& request_json){
    json response;
    response["response_type"]=AGREE_JOIN_CHANNEL;
    response["result"]=0;
    response["msg"]="加入成功";
    response["chat_room_id"]=request_json["chat_room_id"];
    response["user_id"]=request_json["user_id"];

    chat_room_manager.JoinChatRoom(request_json["chat_room_id"],request_json["user_id"],user_manager.get_user_name(request_json["user_id"]));
    user_manager.add_chat_list(request_json["user_id"],request_json["chat_room_id"]);
    // notify_manager.add_notification(Notify::create(request_json));

    ResponseClient(sockfd,response);
};

void handle_refuse_request(const int &sockfd, const json& request_json){
    json response;
    response["response_type"]=AGREE_JOIN_CHANNEL;
    response["result"]=1;
    response["msg"]="拒绝成功";
    response["chat_room_id"]=request_json["chat_room_id"];
    response["user_id"]=request_json["user_id"];

    // notify_manager.add_notification(Notify::create(request_json));

    ResponseClient(sockfd,response);
}

void handle_unknown_request(const int& sockfd){
    json response;
    response["response_type"]=0;
    std::string msg="未知请求";

    ResponseClient(sockfd,response);
}